package com.et114.modules.org.services;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.StringTokenizer;

import net.sf.ehcache.CacheException;

import org.acegisecurity.providers.encoding.Md5PasswordEncoder;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

//import com.et114.modules.org.vo.AclVo;
import com.et114.components.acegi.AcegiContext;
import com.et114.components.acegi.Constants;
import com.et114.components.acegi.cache.AcegiCacheManager;
import com.et114.core.dao.vo.BaseVO;
import com.et114.core.exception.CheckException;
import com.et114.core.services.impl.BaseServicesImpl;
import com.et114.core.utility.FileUploadUtil;
import com.et114.core.utility.StringPool;
import com.et114.modules.org.dao.AclDAO;
import com.et114.modules.org.dao.EmpDao;
import com.et114.modules.org.dao.GroupDao;
import com.et114.modules.org.dao.RoleDAO;
import com.et114.modules.org.dao.TitleDAO;
import com.et114.modules.org.dao.UserDAO;
import com.et114.modules.org.utility.tree.OrgGroupTree;
import com.et114.modules.org.vo.EmpTitleRelVo;
import com.et114.modules.org.vo.FuncComponentVo;
import com.et114.modules.org.vo.FunctionVo;
import com.et114.modules.org.vo.GroupRelVo;
import com.et114.modules.org.vo.GroupRoleRelVO;
import com.et114.modules.org.vo.GroupTitleRelVO;
import com.et114.modules.org.vo.GroupVo;
import com.et114.modules.org.vo.RoleVo;
import com.et114.modules.org.vo.TitleMsgVo;
import com.et114.modules.org.vo.TitleRoleRelVo;
import com.et114.modules.org.vo.UserEmplyVo;
import com.et114.modules.org.vo.UserRoleRelVo;
import com.et114.modules.org.vo.UserVo;


//@author  ZHOUXY , guanhw 
public class GroupManager extends BaseServicesImpl {
    private Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
    private GroupDao groupDao;
    private EmpDao empDao;
    private TitleDAO titleDao;
    private UserDAO userDao;
    private RoleDAO roleDao;
    private AclDAO aclDAO ;
    public static String empCodeBase = "000000" ; 
	private long mSpil = 40 ;
	
	
	public void setAclDAO ( AclDAO aclDAO ) {
		this.aclDAO = aclDAO;
	}
	
	public void setGroupDao ( GroupDao groupDao ) {
		this.groupDao = groupDao;
	}
	
	public void setEmpDao ( EmpDao empDao ) {
		this.empDao = empDao;
	}
	
	public void setTitleDao ( TitleDAO titleDao ) {
		this.titleDao = titleDao;
	}
	
	public void setUserDao ( UserDAO userDao ) {
		this.userDao = userDao;
	}
	
	public void setRoleDao ( RoleDAO roleDao ) {
		this.roleDao = roleDao;
	}
	
	//
	public long getmSpil ( ) {
		return mSpil;
	}
	
	public void setmSpil ( long mSpil ) {
		if ( mSpil >= 35 ) this.mSpil = mSpil;
	}	
	
	public void createGroup ( GroupVo groupVo ) throws CheckException {
		groupDao.createGroup ( groupVo );
		GroupRelVo groupRelVo = new GroupRelVo ( );
		groupRelVo.setFgrpId ( groupVo.getFgrpId ( ) );
		groupDao.createGroupRel ( groupRelVo );
	}
	

	public void createGroup ( GroupVo groupVo , GroupRelVo groupRelVo )
			throws CheckException {
		Long fgId = groupVo.getFgrpId ( ) ; 
		if ( fgId != null && fgId.longValue ( ) != 0L ) {
			int childsCount = countGroups ( fgId ).intValue ( );
			if ( childsCount >= mSpil )
				throw new CheckException (
						"\u7cfb\u7edf\u8bbe\u7f6e\u5b50\u673a\u6784\u6570\u91cf\u4e0d\u80fd\u8d85\u8fc7 ： "
								+ mSpil + "\u4e2a" );
			long grpNo = fgId.longValue ( ) * mSpil;
			if ( childsCount == 0 )
				grpNo = fgId.longValue ( ) * mSpil + ( childsCount + 1 );
			else
				grpNo = groupDao.maxGrpNoByParentId ( fgId ).longValue ( ) + 1;
			
			logger.info ( "grpNo:" + grpNo ) ;
			if ( grpNo < 0 )
				throw new CheckException (
						"\u7ec4\u7ec7\u673a\u6784\u6811\u5c42\u6b21\u8d85\u51fa\u8303\u56f4  \uff01 " );
			groupVo.setGrpNo ( new Long ( grpNo ) );
		}
		groupDao.createGroup ( groupVo );//
		groupRelVo.setGrpId ( groupVo.getGrpId ( ) );
		String fgPath = loadGroupRel ( fgId ) .getGrpPath ( ) ;
		groupRelVo.setGrpPath (  fgPath  +  StringPool.SLE + groupVo.getGrpId ( ) ) ;
		groupDao.createGroupRel ( groupRelVo );
	}
	
	public void updateGroup( GroupVo groupVo , GroupRelVo groupRelVo ) throws CheckException {
		Long fgId = groupVo.getFgrpId ( ) ; 
		if ( fgId != null
				&& fgId.longValue ( ) != 0L
				&& groupVo.getGrpId ( ).longValue ( ) != Constants.ORG_GROUP_BASE_VALUE ) {
			String fgPath = loadGroupRel ( fgId ) .getGrpPath ( ) ;
			groupRelVo.setGrpPath (  fgPath  +  StringPool.SLE + groupVo.getGrpId ( ) ) ;
		}		
		updateGroup( groupVo ) ; 
		groupDao.updateGroupRel ( groupRelVo ) ;
		
		if ( Constants.ORG_GROUP_ENTITY_N .equals ( groupRelVo .getGrpFlag ( ) ) ) {
			if ( groupRelVo.getGrpPath ( ) != null && !groupRelVo.getGrpPath ( ).endsWith ( StringPool.SLE ) )
				groupRelVo.setGrpPath ( groupRelVo.getGrpPath ( ) + StringPool.SLE ) ;
			downUpdateGroupRel( groupRelVo ) ; 
		}
	}
	
	/**
	 * 递归更新 机构类型
	 */
	public void updateGroupRel( GroupRelVo groupRelVo ) throws CheckException { 
		groupDao.updateGroupRel ( groupRelVo ) ;
		if ( groupRelVo.getGrpPath ( ) != null && !groupRelVo.getGrpPath ( ).endsWith ( StringPool.SLE ) )
			groupRelVo.setGrpPath ( groupRelVo.getGrpPath ( ) + StringPool.SLE ) ;		
		downUpdateGroupRel( groupRelVo ) ;		
	}
	
	/**
	 * 递归更新grpFlag
	 */
	private void downUpdateGroupRel( GroupRelVo groupRelVo  )  throws CheckException { 
		Long operuser = groupRelVo.getOperUser ( );
		Long groupId = groupRelVo.getGrpId ( ) ; 
		List childs = getGroupsByPath ( groupRelVo ) ;
		for ( java.util.Iterator iter = childs.iterator ( ) ; iter.hasNext ( ) ;   ) {
			GroupVo group = ( GroupVo ) iter.next ( ) ;
			if ( !groupId.equals ( group.getGrpId ( )  ) ) {
				groupRelVo = new GroupRelVo( ) ;
				groupRelVo.setGrpId ( group.getGrpId ( ) ) ; 
				groupRelVo.setGrpFlag ( Constants.ORG_GROUP_ENTITY_N )	 ;
				groupRelVo.setOperUser ( operuser );
				groupDao.updateGroupRel ( groupRelVo ) ;				
			} 
		}
	}
	

	
	public GroupVo loadRootGroup ( ) throws CheckException {
		return groupDao.loadRootGroup ( );
	}
	
	public GroupVo loadGroup ( Long grpId ) throws CheckException {
		return groupDao.loadGroup ( grpId );
	}
	
	public GroupRelVo loadGroupRel ( Long grpId ) throws CheckException {
		return groupDao.loadGroupRel (  grpId );
	}	
	
	public GroupRelVo loadGroupRelByCode ( String grpCode ) throws CheckException {
		return groupDao.loadGroupRelByCode ( grpCode  );
	}	
	
	public List getGroupsByIds ( Long[] grpIds ) throws CheckException { 
		return groupDao.getGroupsByIds ( grpIds ) ; 
	}
	
	public List getGroupsByIds( String[] grpIds ) throws CheckException {
		Long[] tg = new Long[ grpIds.length  ] ; 
		for (  int i = 0 ; i < grpIds.length ; i ++ ) 
			tg[ i ] = Long.valueOf ( grpIds[ i ] ) ;
		return getGroupsByIds( tg ) ;
	}	
	
	public GroupVo loadGroup ( GroupVo groupVo ) throws CheckException {
		return groupDao.loadGroup ( groupVo.getGrpId ( ) );
	}
	
	public List queryChildGroups ( GroupVo groupVo ) throws CheckException {
		return queryChildGroups ( groupVo.getGrpId ( ) );
	}
	
	public List queryChildGroups ( Long grpId ) throws CheckException {
		return groupDao.queryChildGroups ( grpId );
	}
	
	public List queryTitlesOfGroup ( GroupVo groupVo ) throws CheckException {
		return groupDao.queryTitlesOfGroup ( groupVo.getGrpId ( ) );
	}
	
	public List queryEmpsOfTitle ( Long titleId ) throws CheckException {
		return queryEmpsOfTitle ( titleId );
	}
	
	public int countEmpsOfTitle ( TitleMsgVo titleMsgVo ) throws CheckException {
		return empDao.countEmpsOfTitle ( titleMsgVo ) ; 
	}
	
	
	public List queryEmpsOfTitle ( TitleMsgVo titleMsgVo )	throws CheckException {
		return empDao.queryEmpsOfTitle ( titleMsgVo.getTitleId ( ) );
	}
	
	public int countEmpsOfTitleId ( Long titleId ) throws CheckException { 
		return empDao.countEmpsOfTitleId ( titleId ) ; 
	}
	
	public List getGroupsByPath( GroupRelVo  grpRel ) throws CheckException {  
		return groupDao.getGroupsByPath ( grpRel ) ; 
	}
	
	public synchronized Long  createEmpAndAllRel ( UserEmplyVo userEmplyVo ) throws CheckException , CacheException {
		UserVo userVo = userEmplyVo.getUserVo ( );
		if ( userVo != null ) {
			userVo.setCrtUser ( userEmplyVo.getCrtUser ( ) );
			userVo.setUserEmplyVo ( userEmplyVo );
			userVo.setOperUser ( userEmplyVo.getOperUser ( ) );
			createUserRels( userVo ) ; 
			userEmplyVo.setUserId ( userVo.getUserId ( ) );
		}
		
		Long empId = empDao.createEmp ( userEmplyVo );
		/*
		String empCode = String.valueOf ( Long.parseLong (  GroupManager.empCodeBase ) + empId.longValue ( ) ) ;
		userEmplyVo.setEmpCode ( empCode ) ;
		updateEmp ( userEmplyVo )  ; 
		*/
		mergeEmpTitleRel ( userEmplyVo );
		if ( userVo != null ) fireUserCacheSync ( userVo );
		return empId ;
	}

	/*
	private void createUserRelsCache ( UserVo userVo ) throws CheckException ,	CacheException {
		createUserRels( userVo ) ;
		fireUserCacheSync ( userVo );
	}*/
	
	private void createUserRels ( UserVo userVo ) throws CheckException ,	CacheException {
		userVo.setPassword ( buildMD5Passwd ( UserVo.defaultPassword ) );
		userDao.createUser ( userVo );
		mergeUserRoleRel ( userVo );
	}
	
	private void fireUserCacheSync ( UserVo userVo ) throws CheckException ,	CacheException {
		//AcegiCacheManager.getInstansce ( ).modifyUserInCache ( userVo );
		OrgFactory.getUserManager ( ).userRels ( userVo ) ; 
		AcegiCacheManager.getInstansce ( ).modifyUserInCache ( userVo ) ;
	}
	
	public UserEmplyVo loadEmp ( Long empId ) throws CheckException {
		return empDao.loadEmp ( empId );
	}
	
	public UserEmplyVo loadEmp ( UserEmplyVo userEmplyVo )	throws CheckException {
		return empDao.loadEmp ( userEmplyVo.getEmpId ( ) );
	}
	
	public List queryEmp ( UserEmplyVo userEmplyVo ) throws CheckException {
		return empDao.queryEmp ( userEmplyVo );
	}
	
	public int updateEmp ( UserEmplyVo userEmplyVo ) throws CheckException {
		return empDao.updateEmp ( userEmplyVo );
	}
	
	public  void updateEmpAndUser ( UserEmplyVo userEmplyVo  )
			throws CheckException , CacheException {
		UserVo userVo = userEmplyVo.getUserVo ( );
		if ( userVo != null ) {
			userVo.setUserEmplyVo ( userEmplyVo );
			if ( userVo.getUserId ( ) != null && userVo.getUserId ( ).longValue ( ) != 0L ) { 
				userVo.setUpdtUser ( userEmplyVo.getUpdtUser ( ) );
				updateUserAndAllRel ( userVo );
			} else {
				userVo.setCrtUser ( userEmplyVo.getUpdtUser ( ) );
				createUserRels ( userVo );
				userEmplyVo.setUserId ( userVo.getUserId ( ) );
			}
		}
		updateEmp ( userEmplyVo );
	}

	
	private  void updateUserAndAllRel ( UserVo userVo ) throws CheckException ,
			CacheException {
		userVo.setPassword ( StringUtils.isEmpty ( userVo.getPassword ( ) ) ? userDao
						.getUserById ( userVo.getUserId ( ) ).getPassword ( ) // FIXME
						: buildMD5Passwd ( userVo.getPassword ( ) ) );
		userDao.updateUser ( userVo );
		mergeUserRoleRel ( userVo );
	}

	
	public void removeEmp ( Long empId , Long operuser) throws Exception {
		//delete image 
		UserEmplyVo emp = loadEmp ( empId ) ; 
		if ( emp != null ) {
			FileUploadUtil.removeFile ( emp.getIdPhone1 ( ) ) ; 
			FileUploadUtil.removeFile ( emp.getIdPhone2 ( ) ) ; 
		}
		
		empDao.removeEmp ( empId , operuser );
		EmpTitleRelVo empTitleRelVo = new EmpTitleRelVo ( );
		empTitleRelVo.setEmpId ( empId );
		titleDao.removeEmpTitleRel ( empTitleRelVo );
	}

	
	public void removeEmpWidthRels( Long empId , Long operuser) throws Exception { 
		UserVo user = loadUserByEmp ( empId ) ; 
		if ( user != null ) { // 删除role rels
			UserRoleRelVo urVo = new UserRoleRelVo() ;
			urVo.setUserId (  user.getUserId ( ) ) ; 
			userDao.deleteUserRoleRel ( urVo ) ;
			userDao.removeUser ( user ) ;
			if ( user.getLoginName ( ) != null )
				AcegiCacheManager.getInstansce ( ).getUserCache ( ).removeUserFromCache ( user.getLoginName ( ) ) ;
		}
		// 删除员工 and 与岗位关联关系
		removeEmp ( empId , operuser ) ; 
		//
	}
	
	
	public List queryChildren ( BaseVO baseVO ) throws CheckException {
		if ( baseVO instanceof GroupVo ) {
			List list = queryChildGroups ( ( ( GroupVo ) baseVO ).getGrpId ( ) );
			list.addAll ( queryTitlesOfGroup ( ( ( GroupVo ) baseVO ).getGrpId ( ) ) );
			return list;
		} else if ( baseVO instanceof TitleMsgVo ) {
			return queryEmpsOfTitle ( ( ( TitleMsgVo ) baseVO ).getTitleId ( ) );
		} else {
			throw new CheckException ( "queryChildParty()" );
		}
	}
	
	/**
	 * 直接下属机构、岗位
	 * 
	 * @param groupVo
	 * @return
	 * @throws CheckException
	 */
	public List queryChildren ( GroupVo groupVo ) throws CheckException {
		List list = new ArrayList ( );
		list.addAll ( queryChildGroups ( groupVo ) );
		list.addAll ( queryTitlesOfGroup ( groupVo ) );
		return list;
	}

    /**
     * 完整组织机构，包括机构、岗位和员工
     *
     * @param groupVo
     *            机构根
     * @return
     * @throws CheckException
     */
	public List queryDescendant ( GroupVo groupVo ) throws CheckException {
		List list = new ArrayList ( );
		list.addAll ( queryChildren ( groupVo ) );
		
		for ( int i = 0 ; i < list.size ( ) ; i ++ ) {
			BaseVO child = ( BaseVO ) list.get ( i );
			if ( child instanceof GroupVo ) {
				list.addAll ( queryDescendant ( ( GroupVo ) child ) );
			} else if ( child instanceof TitleMsgVo ) {
				list.addAll ( queryEmpsOfTitle ( ( TitleMsgVo ) child ) );
			}
		}
		return list;
	}

	
	public List queryDescendantEmps ( GroupVo groupVo ) throws CheckException {
		List descendant = queryDescendant ( groupVo );
		List empList = new ArrayList ( );
		for ( int i = 0 ; i < descendant.size ( ) ; i ++ ) {
			if ( ( ( BaseVO ) descendant.get ( i ) ) instanceof UserEmplyVo ) {
				empList.add ( descendant.get ( i ) );
			}
		}
		return empList;
	}

	
	public List queryTitlesOfGroup ( Long grpId ) throws CheckException {
		return groupDao.queryTitlesOfGroup ( grpId );
	}
	
	public void updateTitle ( TitleMsgVo titleMsgVo ) throws CheckException {
		GroupTitleRelVO groupTitleRelVO = new GroupTitleRelVO ( );
		groupTitleRelVO.setGrpId ( titleMsgVo.getGrpId ( ) );
		String tn_ = titleDao.loadTitle ( titleMsgVo.getTitleId ( ) ).getTitleName ( ) ; 
		titleDao.updateTitle ( titleMsgVo );
		
		//update cache
		if ( Constants.CACHE_NAME.equals ( AcegiContext.getOrgCacheKey ( ) ) ) {
			if ( !tn_.equals ( titleMsgVo.getTitleName ( ) ) ) updateTitleModifyInCache( tn_ , titleMsgVo ) ;	
		}
	}
	
	public TitleMsgVo loadTitle ( TitleMsgVo titleMsgVo ) throws CheckException {
		return loadTitle ( titleMsgVo.getTitleId ( ) );
	}
	
	
	public TitleMsgVo loadTitle ( Long titleId ) throws CheckException {
		return titleDao.loadTitle ( titleId );
	}
	
	public void createTitle ( TitleMsgVo titleMsgVo ,	GroupTitleRelVO groupTitleRelVO ) throws CheckException {
		groupTitleRelVO.setTitleId ( titleDao.createTitle ( titleMsgVo ) );
		titleDao.createGroupTitleRel ( groupTitleRelVO );
	}
	
	public void createTitle ( TitleMsgVo titleMsgVo ) throws CheckException {
		GroupTitleRelVO groupTitleRelVO = new GroupTitleRelVO ( );
		groupTitleRelVO.setGrpId ( titleMsgVo.getGrpId ( ) );
		groupTitleRelVO.setCrtUser ( titleMsgVo.getCrtUser ( ) );
		groupTitleRelVO.setOperUser ( titleMsgVo.getOperUser ( ) );
		createTitle ( titleMsgVo , groupTitleRelVO );
	}
	
	/**
	 * // since 1.68
	 * 修改岗位名称 更新cache
	 * @param tn
	 * @param title
	 * @throws CheckException
	 * @throws CacheException
	 */
	private void updateTitleModifyInCache( String tn , TitleMsgVo title  ) throws CheckException , CacheException { 
		List funcs = titleDao.getFunctionsByTitle ( title.getTitleId ( ) ) ; 
		List funcEls =  titleDao.getFuncComponentsByTitle ( title.getTitleId ( ) )  ;
		List emps = empDao.queryEmpsOfTitleId( title.getTitleId ( ) ) ;  //主岗
		emps.addAll ( empDao.queryEmpsOfTitle( title.getTitleId ( ) ) ) ; 
		
		if ( Constants.CACHE_NAME.equals ( AcegiContext.getOrgCacheKey ( ) ) ) { 
			for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( ) ;  ) {
				FunctionVo resource = ( FunctionVo ) iter.next ( );
				//OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
				if ( AcegiCacheManager.getInstansce ( ).getAuthorityFromCache ( resource.getResString ( ) ) == null ) {
					logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
					OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
				}
				else 				
					AcegiCacheManager.getInstansce ( ).modAuthorityCache (
							Constants.RESOURCE ,
							resource.getResString ( ) ,
							title.getTitleId ( ) + StringPool.DASH + tn ,
							title.getTitleId ( ) + StringPool.DASH + title.getTitleName ( ) ,
							Constants.AUTH_TYPE_TITLE );
			}
			
			for ( java.util.Iterator iter = funcEls.iterator ( ) ; iter.hasNext ( ) ;  ) {
				FuncComponentVo resource = ( FuncComponentVo ) iter.next ( );
				//OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
				if ( AcegiCacheManager.getInstansce ( ).getAuthorityFromCache ( resource.getResString ( ) ) == null ) {
					logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
					OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
				}
				else 								
					AcegiCacheManager.getInstansce ( ).modAuthorityCache (
							Constants.RESOURCE ,
							resource.getResString ( ) ,
							title.getTitleId ( ) + StringPool.DASH + tn ,
							title.getTitleId ( ) + StringPool.DASH + title.getTitleName ( ) ,
							Constants.AUTH_TYPE_TITLE );				
			}
			
			for ( java.util.Iterator iter = emps.iterator ( ) ; iter.hasNext ( ) ;  ) {
				UserEmplyVo emp = ( UserEmplyVo ) iter.next ( ) ; 
				Long userId = emp.getUserId ( ) ;
				if ( userId != null && userId.longValue ( ) != 0 ) {
					UserVo user = userDao.getUserById ( userId ) ;
					if ( user != null ) {
						//OrgFactory.getUserManager ( ).modifyInCache (  user ) ;
						if ( AcegiCacheManager.getInstansce ( ).getUserDetailsByUserId ( user.getLoginName ( ) ) == null ) {
							logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
							OrgFactory.getUserManager ( ).modifyInCache (  user ) ;
						}
						else 														
							AcegiCacheManager.getInstansce ( ).modAuthorityCache (
									Constants.PRINCIPAL ,
									user.getLoginName ( ) ,
									title.getTitleId ( ) + StringPool.DASH + tn ,
									title.getTitleId ( ) + StringPool.DASH + title.getTitleName ( ) ,
									Constants.AUTH_TYPE_TITLE );				
					}
				}
			}				
		}
		
	}
	// since 1.68
	public void titleRoleRelmodifyInCache( Long titleId , List roles , byte mm ) throws CheckException , CacheException {
		if ( roles == null || roles.size ( ) == 0 ) return ; 
		if ( titleId == null || titleId.longValue ( ) == 0L ) return ;
		Object[] objs = new Object[ roles.size ( ) ] ;
		for ( int  i = 0 ; i < roles.size ( )  ; i ++ ) {
			RoleVo role = ( RoleVo ) roles.get ( i ); 
			if ( Constants.CACHE_NAME.equals ( AcegiContext.getOrgCacheKey ( ) ) ) 
				objs[ i ] =  role.getRoleName ( ) ;
			else objs[ i ] = role.getRoleId ( ) ;
		}
		
		List funcs = titleDao.getFunctionsByTitle ( titleId ) ; 
		List funcEls =  titleDao.getFuncComponentsByTitle ( titleId )  ;
		List emps = empDao.queryEmpsOfTitleId( titleId ) ;  //主岗
		emps.addAll ( empDao.queryEmpsOfTitle( titleId ) ) ; 
		
		for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FunctionVo resource = ( FunctionVo ) iter.next ( );
			if ( AcegiCacheManager.getInstansce ( ).getAuthorityFromCache ( resource.getResString ( ) ) == null ) {
				logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
				OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
			}
			else 
				AcegiCacheManager.getInstansce ( )
				   .modResourceAuthorityCache ( resource.getResString ( ) ,
						   mm , Constants.AUTH_TYPE_ROLE ,  objs );
		}
		
		for ( java.util.Iterator iter = funcEls.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FuncComponentVo resource = ( FuncComponentVo ) iter.next ( );
			if ( AcegiCacheManager.getInstansce ( ).getAuthorityFromCache ( resource.getResString ( ) ) == null ) {
				logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
				OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
			}
			else 			
				AcegiCacheManager.getInstansce ( )
				   .modResourceAuthorityCache ( resource.getResString ( ) ,
						   mm , Constants.AUTH_TYPE_ROLE ,  objs );
		}
		
		for ( java.util.Iterator iter = emps.iterator ( ) ; iter.hasNext ( ) ;  ) {
			UserEmplyVo emp = ( UserEmplyVo ) iter.next ( ) ; 
			Long userId = emp.getUserId ( ) ;
			if ( userId != null && userId.longValue ( ) != 0 ) {
				UserVo user = userDao.getUserById ( userId ) ;
				if ( user != null ) {
					if ( AcegiCacheManager.getInstansce ( ).getUserDetailsByUserId ( user.getLoginName ( ) ) == null ) {
						logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
						OrgFactory.getUserManager ( ).modifyInCache (  user ) ;
					}
					else 								
						AcegiCacheManager.getInstansce ( ).modUserAuthorityCache (
								user.getLoginName ( ) , mm , Constants.AUTH_TYPE_ROLE ,
								objs , false );					
				}
			}
		}		
	}
	
	// since 1.68
	public void titleRoleRelmodifyInCache( Long titleId , Long[] roleIds , byte mm ) throws CheckException , CacheException { 
		if ( roleIds != null && roleIds.length > 0 && titleId != null ) {
			RoleVo vo = new RoleVo( ) ; 
			vo.setRoleIds ( roleIds ) ; 
			List roles = roleDao.getRoles ( vo ) ;
			titleRoleRelmodifyInCache( titleId , roles , mm ) ; 
		}
	}
	
	// since 1.68 de
	public void modifyInCache(  TitleRoleRelVo titleRoleRel , byte mm ) throws CheckException , CacheException {
		Object obj = titleRoleRel.getRoleId ( ) ; 
		if ( Constants.CACHE_NAME.equals ( AcegiContext.getOrgCacheKey ( ) ) ) { 
			RoleVo role = roleDao.getRoleById ( titleRoleRel.getRoleId ( ) ) ;
			obj = role.getRoleName ( ) ; 
		}
		
		List funcs = titleDao.getFunctionsByTitle ( titleRoleRel.getTitleId ( ) ) ; 
		List funcEls =  titleDao.getFuncComponentsByTitle ( titleRoleRel.getTitleId ( ) )  ;
		List emps = empDao.queryEmpsOfTitleId( titleRoleRel.getTitleId ( ) ) ;  //主岗
		emps.addAll ( empDao.queryEmpsOfTitle( titleRoleRel.getTitleId ( ) ) ) ; 

		for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FunctionVo resource = ( FunctionVo ) iter.next ( );
			//OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
			if ( AcegiCacheManager.getInstansce ( ).getAuthorityFromCache ( resource.getResString ( ) ) == null ) {
				logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
				OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
			}
			else 			
				AcegiCacheManager.getInstansce ( )
				   .modResourceAuthorityCache ( resource.getResString ( ) ,
						   mm , Constants.AUTH_TYPE_ROLE ,  new Object[ ] { obj } );
		}
		
		for ( java.util.Iterator iter = funcEls.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FuncComponentVo resource = ( FuncComponentVo ) iter.next ( );
			//OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ;
			if ( AcegiCacheManager.getInstansce ( ).getAuthorityFromCache ( resource.getResString ( ) ) == null ) {
				logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
				OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
			}
			else 						
				AcegiCacheManager.getInstansce ( )
				   .modResourceAuthorityCache ( resource.getResString ( ) ,
						   mm , Constants.AUTH_TYPE_ROLE ,  new Object[ ] { obj } );			
		}
		
		for ( java.util.Iterator iter = emps.iterator ( ) ; iter.hasNext ( ) ;  ) {
			UserEmplyVo emp = ( UserEmplyVo ) iter.next ( ) ; 
			Long userId = emp.getUserId ( ) ;
			if ( userId != null && userId.longValue ( ) != 0 ) {
				UserVo user = userDao.getUserById ( userId ) ;
				if ( user != null ) {
					//OrgFactory.getUserManager ( ).modifyInCache (  user ) ;
					if ( AcegiCacheManager.getInstansce ( ).getUserDetailsByUserId ( user.getLoginName ( ) ) == null ) {
						logger.warn ( "ALLWAYS:WARN>> cache warn !"  ) ; 
						OrgFactory.getUserManager ( ).modifyInCache (  user ) ;
					}
					else 													
						AcegiCacheManager.getInstansce ( ).modUserAuthorityCache (
								user.getLoginName ( ) , mm , Constants.AUTH_TYPE_ROLE ,
								new Object [ ] { obj } , false  );					
				}
			}
		}				
	}
	
	// 更新所有
	public void modifyInCache(  Long titleId ) throws CheckException , CacheException {
		List funcs = titleDao.getFunctionsByTitle ( titleId ) ; 
		List funcEls =  titleDao.getFuncComponentsByTitle ( titleId )  ;
		List emps = empDao.queryEmpsOfTitleId( titleId ) ;  //主岗
		emps.addAll ( empDao.queryEmpsOfTitle( titleId ) ) ; 
		
		for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FunctionVo resource = ( FunctionVo ) iter.next ( );
			OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
		}
		
		for ( java.util.Iterator iter = funcEls.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FuncComponentVo resource = ( FuncComponentVo ) iter.next ( );
			OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
		}
		
		for ( java.util.Iterator iter = emps.iterator ( ) ; iter.hasNext ( ) ;  ) {
			UserEmplyVo emp = ( UserEmplyVo ) iter.next ( ) ; 
			Long userId = emp.getUserId ( ) ;
			if ( userId != null && userId.longValue ( ) != 0 ) {
				UserVo user = userDao.getUserById ( userId ) ;
				if ( user != null ) {
					OrgFactory.getUserManager ( ).modifyInCache (  user ) ;
				}
			}
		}		
	}
	
	/*//TODO 
	 * 删除rel group
	 * 删除rel auth
	 * 删除rel user
	 */
	public  synchronized void removeTitle ( Long titleId ,Long operuser ) throws CheckException , CacheException {
		//删除与组的管理信息
		GroupTitleRelVO groupTitleRelVO = new GroupTitleRelVO ( );
		groupTitleRelVO.setTitleId ( titleId ) ; 
		groupTitleRelVO.setOperUser ( operuser );
		titleDao.deleteGroupTitleRel ( groupTitleRelVO ); 
		List funcs = titleDao.getFunctionsByTitle ( titleId ) ; 
		List funcEls =  titleDao.getFuncComponentsByTitle ( titleId )  ; 
		List emps = empDao.queryEmpsOfTitleId( titleId ) ;  //主岗
		//List roles = titleDao.getRolesByTitle ( titleId ) ;
		emps.addAll ( empDao.queryEmpsOfTitle( titleId ) ) ; 

		//删除岗位授权信息
		aclDAO.deleteAclByTitleId ( titleId , operuser ) ; 
		//删除兼职信息
		EmpTitleRelVo etr  = new EmpTitleRelVo( ) ; 
		etr.setTitleId ( titleId ) ; 
		removeEmpTitleRel( etr ) ; 
		//删除主岗信息
		empDao.updateEmpPrimaryTitleISNULL( titleId ) ; 
		//删除岗位信息
		titleDao.deleteTitle ( titleId , operuser );
		//删除岗位角色关系
		titleDao.deleteTitleRoleRelByTitleId ( titleId , operuser);
		
		for ( java.util.Iterator iter = funcs.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FunctionVo resource = ( FunctionVo ) iter.next ( );
			OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ;
		}
		
		for ( java.util.Iterator iter = funcEls.iterator ( ) ; iter.hasNext ( ) ;  ) {
			FuncComponentVo resource = ( FuncComponentVo ) iter.next ( );
			OrgFactory.getFunctionManager ( ).modifyInCache (  resource ) ; 
		}
		
		for ( java.util.Iterator iter = emps.iterator ( ) ; iter.hasNext ( ) ;  ) {
			UserEmplyVo emp = ( UserEmplyVo ) iter.next ( ) ; 
			Long userId = emp.getUserId ( ) ;
			if ( userId != null && userId.longValue ( ) != 0 ) {
				UserVo user = userDao.getUserById ( userId ) ;
				if ( user != null ) {
					OrgFactory.getUserManager ( ).modifyInCache (  user ) ;
				}
			}
		}		
	}	
	
	public UserVo loadUserByEmp ( Long empId ) throws CheckException {
		return ( UserVo ) userDao.loadUserByEmp ( empId );
	}
	
	public List queryEmpByUser ( Long userId ) throws CheckException {
		return empDao.queryEmpByUser ( userId );
	}
	
	public UserEmplyVo loadEmpByUser ( Long userId ) throws CheckException {
		return empDao.loadEmpByUser ( userId );
	}
	
	public UserEmplyVo loadEmpWithTitlesByUser ( Long userId ) throws CheckException {
		UserEmplyVo userEmplyVo = empDao.loadEmpByUser ( userId );
		if ( userEmplyVo != null ) {
			userEmplyVo.setTitleMsgVo ( loadPrimaryTitleOfUser ( userId ) );
			userEmplyVo.setTitleList ( queryTitlesOfEmp ( userEmplyVo.getEmpId ( ) ) );
		}
        return userEmplyVo;
    }

    public TitleMsgVo loadPrimaryTitleOfUser(Long userId) throws CheckException {
        return (TitleMsgVo) titleDao.loadPrimaryTitleOfUser(userId);
    }

    public Long countEmpCode(String empCode) throws CheckException {
        return empDao.countEmpCode(empCode);
    }

	
	public UserEmplyVo loadEmpByEmpCode ( String empCode ) throws CheckException {
		return ( UserEmplyVo ) empDao.loadEmpByEmpCode ( empCode );
	}


	
	public List queryTitlesOfUser ( Long userId ) throws CheckException {
		return titleDao.queryTitlesOfUser ( userId );
	}
	
	public List queryTitlesOfEmp ( Long empId ) throws CheckException {
		return titleDao.queryTitlesOfEmp ( empId );
	}
	
	public Long countLoginName ( String loginName ) throws CheckException {
		return userDao.countLoginName ( loginName );
	}
	
	public UserVo loadUserByLoginName ( String loginName )
			throws CheckException {
		return ( UserVo ) userDao.loadUserByLoginName ( loginName );
	}

    public void createEmpTitleRel(EmpTitleRelVo empTitleRelVo) throws CheckException {
        titleDao.createEmpTitleRel(empTitleRelVo);
    }

    public void removeEmpTitleRel(EmpTitleRelVo empTitleRelVo) throws CheckException {
        titleDao.removeEmpTitleRel(empTitleRelVo);
    }

	


    // TODO batch operate; updt info miss
	public synchronized void updateEmpAndAllRel ( UserEmplyVo userEmplyVo , boolean isUser ) throws CheckException , CacheException {
			if ( userEmplyVo.getUserId ( ) != null && 
					userEmplyVo.getUserId ( ).longValue ( ) != 0 	) {
				UserVo vo = userDao.getUserById ( userEmplyVo.getUserId ( ) ) ;
				if ( !isUser   ) {
					if ( vo != null  ) {
						//删除用户
						String loginName = vo.getLoginName ( ) ; 
						userDao.removeUser ( vo ) ; 
						//删除用户角色关系
						UserRoleRelVo userRoleRelVo = new UserRoleRelVo ( );
						userRoleRelVo.setUserId ( vo.getUserId ( ) );
						userDao.deleteUserRoleRel ( userRoleRelVo ); // rm user's
						//删除缓存
						AcegiCacheManager.getInstansce ( ).getUserCache ( ).removeUserFromCache ( loginName ) ;
						userEmplyVo.setUserId ( null ) ; 
						userEmplyVo.setUserVo ( null ) ;
					}
				}
				else {
					if ( isUser )
						if ( Constants.JOBSTATE_OUT.equals ( userEmplyVo.getJobState ( ) )  ) {
							String loginName =  userEmplyVo.getUserVo ( ).getLoginName ( ) ; 
							UserRoleRelVo userRoleRelVo = new UserRoleRelVo ( );
							userRoleRelVo.setUserId ( vo.getUserId ( ) );
							userDao.deleteUserRoleRel ( userRoleRelVo ); // rm user's
							//删除缓存
							AcegiCacheManager.getInstansce ( ).getUserCache ( ).removeUserFromCache ( loginName ) ;
							
							userEmplyVo.getUserVo ( ).setWorkFlg ( Boolean.FALSE ) ;
						}						
					
					userEmplyVo.getUserVo ( ).setPassword ( null ) ;
				}
			}
		updateEmpAndUser ( userEmplyVo );
		mergeEmpTitleRel ( userEmplyVo );
		if ( userEmplyVo.getUserVo ( ) != null ) fireUserCacheSync ( userEmplyVo.getUserVo ( ) );
	}

	
	private String buildMD5Passwd ( String password ) {
		return md5PasswordEncoder.encodePassword ( password , null );
	}
	
	public void mergeUserRoleRel ( UserVo userVo ) throws CheckException {
		List roleList = userVo.getRoleList ( );
		if ( roleList == null )
			return;
		// caution, reuse userRoleRelVo
		UserRoleRelVo userRoleRelVo = new UserRoleRelVo ( );
		userRoleRelVo.setUserId ( userVo.getUserId ( ) );
		userDao.deleteUserRoleRel ( userRoleRelVo ); // rm user's all roles
		userRoleRelVo.setCrtUser ( userVo.getCrtUser ( ) != null ? userVo
				.getCrtUser ( ) : userVo.getUpdtUser ( ) );
		
		if ( roleList.size ( ) > 0 ) {
			for ( int i = 0 ; i < roleList.size ( ) ; i ++ ) {
				userRoleRelVo.setRoleId ( ( ( RoleVo ) roleList.get ( i ) ).getRoleId ( ) );
				userDao.createUserRoleRel ( userRoleRelVo );
			}
		}
	}

    /**
     * TODO remove employee's all titles(include redundant primary title) then rebuild all of them
     *
     * @param userEmplyVo
     * @throws CheckException
     */
	private void mergeEmpTitleRel ( UserEmplyVo userEmplyVo ) throws CheckException {
        List titleList = userEmplyVo.getTitleList();
		if ( titleList == null ) return;

		if (  userEmplyVo.getTitleId ( )  != null ) {
			if ( userEmplyVo.getTitleId ( ) .longValue ( ) == 0  ) userEmplyVo.setTitleId ( null ) ; 
		}
		
		List oldTitles = queryTitlesOfEmp( userEmplyVo.getEmpId ( ) )  ;
		
		List jTitles = new ArrayList() ; 
		jTitles.addAll ( titleList ) ; 
		if ( ! jTitles.retainAll ( oldTitles )  ) {
			jTitles.clear ( ) ; 
			jTitles.addAll ( oldTitles ) ; 
			jTitles.retainAll ( titleList ) ; 
		}

		//new 
		titleList.removeAll ( jTitles ) ;
		//del
		oldTitles.removeAll ( jTitles ) ;
		
		//common
		EmpTitleRelVo empTitleRelVo = new EmpTitleRelVo ( );
		empTitleRelVo.setEmpId ( userEmplyVo.getEmpId ( ) ) ; 

		for ( java.util.Iterator iter = oldTitles.iterator ( ) ; iter.hasNext ( ) ;  ) {
			TitleMsgVo title = ( TitleMsgVo )  iter.next ( ) ; 
			// rm emp's all titles
			empTitleRelVo.setTitleId ( title.getTitleId ( ) ) ;
			empTitleRelVo.setOperUser ( userEmplyVo.getOperUser ( ) );
			removeEmpTitleRel ( empTitleRelVo );
		}
		

		empTitleRelVo.setCrtUser ( userEmplyVo.getCrtUser ( ) );
        // re create emp's title
		if ( titleList.size ( ) > 0 ) {
 //           updateEmp( userEmplyVo );
            //
			for ( int i = 0 ; i < titleList.size ( ) ; i ++ ) {
				Long titleId = ( ( TitleMsgVo ) titleList.get ( i ) ).getTitleId ( ) ; 
				empTitleRelVo.setTitleId ( titleId );
				empTitleRelVo.setOperUser ( userEmplyVo.getOperUser ( ) );
				createEmpTitleRel ( empTitleRelVo );
			}
			updateEmpPrimaryTitle ( userEmplyVo );
        }
        else {
			updateEmpPrimaryTitle ( userEmplyVo );
		}
    }

	
	public List queryEmpWithTitleList ( GroupVo groupVo ) throws CheckException {
		return empDao.queryEmpWithTitleList ( groupVo );
	}
	
	public Long countEmpWithTitles( GroupVo groupVo ) throws CheckException { 
		return empDao.countEmpWithTitles ( groupVo  ) ; 
	}
	
	public List queryEmpsOfGroup ( GroupVo groupVo ) throws CheckException {
		return empDao.queryEmpsOfGroup ( groupVo );
	}
	
	public void updateGroup ( GroupVo groupVo ) throws CheckException {
		groupDao.updateGroup ( groupVo );
	}
	
	public void removeGroup ( Long grpId , Long operuser) throws CheckException {
		groupDao.removeGroup ( grpId , operuser);
	}
	
	public void removeGroupRel ( Long grpId , Long operuser) throws CheckException {
		groupDao.removeGroupRel ( grpId , operuser);
	}

	
	public UserEmplyVo loadEmpWithUser ( Long empId ) throws CheckException {
		UserEmplyVo userEmplyVo = loadEmp ( empId );
		userEmplyVo.setUserVo ( loadUserByEmp ( empId ) );
		return userEmplyVo;
	}

    public List queryTitleNodesOfGroup(Long grpId) throws CheckException {
        // TODO node info
    	return groupDao.queryTitlesOfGroup ( grpId );
    }

	
	public List queryChildGroupNodes ( GroupVo groupVo ) throws CheckException {
		return queryChildGroups ( groupVo );
    }
    
	//author fengmiao
	public List queryTitlesByIds ( Long [ ] titleIds  ) throws CheckException {
			TitleMsgVo vo  = new TitleMsgVo( ) ;
			vo.setTitleIds ( titleIds ) ; 
			return  titleDao.loadTitlesByIds ( vo ) ; 
	}
	


	public int updateEmpPrimaryTitle ( UserEmplyVo userEmplyVo )
			throws CheckException {
		return empDao.updateEmpPrimaryTitle ( userEmplyVo );
	}
	


	// TODO batch del tit
	public synchronized void batchRemoveTitles ( Long [ ] titleIds ,Long operuser) throws CheckException {
		for ( int i = 0 ; i < titleIds.length ; i ++ ) {
			removeTitle ( titleIds[ i ] ,operuser);
		}
	}

	
	public void batchRemoveGroups ( Long [ ] deleteId , Long operuser) throws CheckException {
		for ( int i = 0 ; i < deleteId.length ; i ++ ) {
			removeGroup ( deleteId [ i ] , operuser);
		}
	}
	
	public void batchRemoveGroupRel ( Long [ ] deleteId , Long operuser) throws CheckException {
		for ( int i = 0 ; i < deleteId.length ; i ++ ) {
			removeGroupRel ( deleteId [ i ] , operuser);
			removeGroupRoleRel( new GroupRoleRelVO( deleteId [ i ], null  ) ) ;
		}
	}
	
	
	public GroupVo loadParentGroup ( Long grpId ) {
		return groupDao.loadParentGroup ( grpId );
	}
	
	public GroupVo loadParentGroup ( GroupVo groupVo ) {
		return groupDao.loadParentGroup ( groupVo.getGrpId ( ) );
	}
	
	public GroupVo getGroupWithParents ( GroupVo group ) {
		if ( group != null ) {
			GroupVo parent = loadParentGroup ( group.getGrpId ( ) );
			if ( parent != null ) {
				group.setParentGroupVo ( parent );
				List tmp = new ArrayList ( );
				parent.setChildren ( tmp );
				parent.getChildren ( ).add ( group );
				group = getGroupWithParents ( parent );
			}
		}
		return group;
	}
	
	//
	
	public Map listToMapKeyGrpId( List list )  {
		Map map = new TreeMap( ) ; 
		for ( java.util.Iterator iter = list.iterator ( ) ; iter.hasNext ( ) ;  ) {
			GroupVo _tmp= ( GroupVo ) iter.next ( );
			map.put ( _tmp.getGrpId ( ) , _tmp ) ;
		}
		return map ;
	}
	
	
	/**
	 * 检查当前用户是否具有管理 grpId 
	 * @param userId
	 * @param grpId
	 * @return
	 * @throws CheckException
	 */
	public boolean checkGrpManager( Long userId , Long grpId ) throws CheckException {
			List roles = OrgFactory.getUserManager ( ).getAllRolesByUserParams  (
					Constants.ROLE_TYPE_ORG_MANAGER , userId );
			if ( roles.size ( ) > 0 ) {
				StringBuffer roleIds = new StringBuffer() ;
				for ( int i = 0 ; i < roles.size ( ) ; i ++ ) {
					RoleVo role = ( RoleVo ) roles.get ( i ) ;
					roleIds.append ( role.getRoleId ( ).toString ( ) )  ;
					if ( ( i + 1 ) != roles.size ( ) ) roleIds.append ( StringPool.COMMA )  ;
				}
				if ( roleIds.length ( ) > 0 ) {
					Map map = OrgFactory.getRoleManager ( ).getGroupsAnByRoles ( roleIds.toString ( ) ) ;
					if ( map.containsKey ( grpId ) ) return true ; 
				}
			} 
			return false ;
	}    
	
	public GroupVo loadGroup4SelectOption ( Long grpId ) {
		GroupVo groupVo = null;
		if ( grpId != null && grpId.longValue ( ) != 0L ) 
			groupVo = loadGroup ( grpId );
		 else groupVo = loadRootGroup ( );
		
		/*GroupVo parentGroupVo = loadParentGroup ( groupVo );
		groupVo.setParentGroupVo ( parentGroupVo );
		List childGroupList = queryChildGroups ( groupVo );
		groupVo.setChildGroupList ( childGroupList );
		List titleList = queryTitlesOfGroup ( groupVo.getGrpId ( ) );
		groupVo.setTitleList ( titleList );*/
		return groupVo;
	}
    
	
	public Long countTitles ( TitleMsgVo titleMsgVo ) throws CheckException {
		return titleDao.countTitles ( titleMsgVo );
	}
	
	public Long countGroups ( GroupVo groupVo ) throws CheckException {
		return groupDao.countGroups ( groupVo );
	}
	
	public Long countGroups( Long fgrpId ) throws CheckException { 
		GroupVo groupVo = new GroupVo ( ) ; 
		groupVo.setFgrpId ( fgrpId ) ;
		return countGroups( groupVo ) ; 
	}
	
	public List getGroupTrees ( GroupVo groupVo ) throws CheckException {
		return groupDao.getGroupTrees ( groupVo );
	}
	
	public void moveGroupRel ( GroupRelVo groupRelVo ) throws CheckException {
		groupDao.moveGroupRel ( groupRelVo );
		
		Long fgId = groupRelVo.getFgrpId ( ) ; 
		if ( fgId != null && fgId.longValue ( ) != 0L ) {
			long grpNo = fgId.longValue ( ) * mSpil + ( countGroups ( fgId ).longValue ( ) + 1 ) ;
			GroupVo groupVo = loadGroup ( groupRelVo.getGrpId ( ) ) ; 
			groupVo.setGrpNo ( new  Long ( grpNo ) ) ;
			updateGroup ( groupVo ) ;
		}
	}
	
	public void updateEmpOfGroup ( UserEmplyVo userEmplyVo )
			throws CheckException {
		groupDao.updateEmpOfGroup ( userEmplyVo );
	}
	
	public List getEmpJobstate ( UserEmplyVo userEmplyVo )
			throws CheckException {
		return groupDao.getEmpJobstate ( userEmplyVo );
	}

    public Long countMoveGroups ( GroupRelVo groupRelVo ) throws CheckException {
		return groupDao.countMoveGroups( groupRelVo );
	}
    
    public Long countIdNOByIdType ( UserEmplyVo userEmplyVo ) throws CheckException {
		return empDao.countIdNOByIdType ( userEmplyVo );
	}
    
    public List getOnlineUser ( UserEmplyVo userEmplyVo ) throws CheckException {
		return empDao.getOnlineUser ( userEmplyVo );
	}
    
    public List loadChildGroup ( Long grpId ) throws CheckException {
		return groupDao.loadChildGroup ( grpId );
	}
    
    public List getRootGroup ( ) throws CheckException {
		return groupDao.getRootGroup ( );
	}
    
    public List getChildGroup ( Long grpId ) throws CheckException {
		return groupDao.getChildGroup ( grpId );
	}
    
    
    
    public  String generateGroupTreeStr ( OrgGroupTree orgGroupTree ) throws CheckException { 
    	Assert.notNull ( orgGroupTree ) ; 
    	StringBuffer sb = new StringBuffer ( );
    	boolean isLeaf = !orgGroupTree.isRoot ( ) ;
    	String funcRootText =  orgGroupTree.getBaseName ( ) == null ? "" : orgGroupTree.getBaseName ( ) ; 
		String funcTargetAction = orgGroupTree.getHref ( ) == null ? "" : orgGroupTree.getHref ( ); 
		String funcSubUrlAction = orgGroupTree.getSrc ( ) == null ? "" :  orgGroupTree.getSrc ( ); 
		List list = orgGroupTree.getChildNodes ( ) == null ? new ArrayList ( ) : orgGroupTree.getChildNodes ( ) ;
		if ( ! isLeaf ) {
			sb.append ( "<gyj:tree pic='root' nodeId=\"-1\" text=\"" + funcRootText + "\" " );		
			if ( orgGroupTree.getLocValue ( ) != null ) sb.append ( " locvalue=" ).append ( "\"" +  orgGroupTree.getLocValue ( )  + "\" "  ) ;
			if ( orgGroupTree.getIsTarget ( ) != null ) sb.append ( " isTarget=" ).append ( "\"" +  orgGroupTree.getIsTarget ( )  + "\" "  ) ;
			//if ( orgGroupTree.getTxtOnclick ( ) != null ) sb.append ( " txtonclick=" ).append ( "\"" +  orgGroupTree.getTxtOnclick ( )  + "\" "  ) ;			
			sb.append ( " >\n" ) ;	
		}
		List childlist = new ArrayList( );
		for ( int i = 0 ; i < list.size ( ) ; i ++ ) {
			GroupVo node = ( GroupVo ) list.get ( i );
			Long id = node.getGrpId ( );
			String name = node.getChnName ( );
			childlist = node.getChildGroupList ( ) ;
			boolean leaf = childlist.size ( ) == 0 ? true : false;
			if ( leaf ) {// 叶子 
				sb.append ( "    <gyj:tree  text=\"" + name + "\" " ) ;  
			}
			else if ( ! leaf ) {
				sb.append ( "    <gyj:tree  src=\"" + funcSubUrlAction + "grpId="
						+ id + "\"" + "  " + "  text=\""
						+ name + "\" " );
			}
			if ( orgGroupTree.getHref ( ) != null ) sb.append ( " href=" ).append ( "\"" +   funcTargetAction + "grpId="  ).append (  id + "\" "  ) ; ;
			if ( orgGroupTree.getTarget ( ) != null ) sb.append ( " target=" ).append ( "\"" +   orgGroupTree.getTarget ( ) + "\" "  ) ;
		    sb.append ( " nodeId=" ).append ( "\"" +  id  + "\" "  ) ;
			if ( orgGroupTree.getOnclick ( ) != null ) sb.append ( " onclick=" ).append ( "\"" +  orgGroupTree.getOnclick ( ) + "\" "   ) ;
			if ( orgGroupTree.getOndbClick ( ) != null ) sb.append ( " ondblclick=" ).append ( "\"" + orgGroupTree.getOndbClick ( ) + "\" " ) ;
			if ( orgGroupTree.getTxtOnclick ( ) != null ) sb.append ( " txtonclick=" ).append ( "\"" +  orgGroupTree.getTxtOnclick ( )  + "\" "  ) ;
		    sb.append ( " />\n" ) ;			
		}
		if ( ! isLeaf ) sb.append ( "</gyj:tree>\n" );
		return sb.toString ( );    	
		
    }
    
	

    
    
	public List getRolesByGrpId ( Long grpId )  throws CheckException {
		return groupDao.getRolesByGrpId ( grpId ) ; 
	}
	
	public int countRolesByGrpId ( Long grpId )  throws CheckException {
		return groupDao.countRolesByGrpId ( grpId ) ; 
	}
	
	public void createGroupRoleRel( GroupRoleRelVO groupRoleRel ) throws CheckException { 
		groupDao.createGroupRoleRel ( groupRoleRel ) ; 
	}
	
	public void createGroupRoleRel( Long crtUser , Long grpId , String principalIds  )  throws CheckException {  
		List roles = new ArrayList( ) ; 
		List tmpRoles = new java.util.ArrayList();
		if ( principalIds != null ) {
			roles = getRolesByGrpId( grpId ) ;
			principalIds = principalIds.trim ( ) ; 
			StringTokenizer st = new StringTokenizer( principalIds , StringPool.SEMICOLON ) ;
			int count = st.countTokens ( ) ;
			for ( int i = 0 ; i < count ; i ++  ) {
				String nt = st.nextToken ( ) ;
				//check
				boolean mark = false ;
				if ( roles.size() == 0  )  mark = true;
				for ( Iterator iter = roles.iterator ( ); iter.hasNext ( ) ;  ) {
					RoleVo role = ( RoleVo )  iter.next ( );
					Long roleId = role.getRoleId ( );
					if ( roleId .toString ( ).equals ( nt ) ) {
						iter.remove ( );
						mark = false ;
						break;
					}
					else mark = true ;
				}
				if ( mark  ) tmpRoles.add ( nt ) ;
			}	
				for ( Iterator iter = tmpRoles.iterator ( ); iter.hasNext ( ) ;  ) {
					Long principalId = Long.valueOf ( iter.next ( ).toString ( ) ) ;
					GroupRoleRelVO groupRoleRel = new GroupRoleRelVO() ;
					groupRoleRel.setRoleId ( principalId ) ;
					groupRoleRel.setGrpId ( grpId );
					groupRoleRel.setCrtUser ( crtUser ) ; 
					createGroupRoleRel( groupRoleRel ) ;
				}	
				
				for ( Iterator iter = roles.iterator ( ); iter.hasNext ( ) ;  ) {
					RoleVo role = ( RoleVo )  iter.next ( );
					Long principalId = role.getRoleId ( );
					GroupRoleRelVO groupRoleRel = new GroupRoleRelVO() ;
					groupRoleRel.setRoleId ( principalId ) ;
					groupRoleRel.setGrpId ( grpId ) ; 
					groupRoleRel.setOperUser ( crtUser );
					removeGroupRoleRel ( groupRoleRel ) ;
				}
		}		
	}
	
	public void updateGroupRoleRel( GroupRoleRelVO groupRoleRel ) throws CheckException { 
		groupDao.updateGroupRoleRel ( groupRoleRel )  ;
	}	
	
	public void removeGroupRoleRel( GroupRoleRelVO groupRoleRel ) throws CheckException {  
		groupDao.deleteGroupRoleRel ( groupRoleRel ) ; 
	}    
	
	public void removeGroupRoleRel( Long grpId , Long roleId , Long operuser ) throws CheckException {  
		GroupRoleRelVO groupRoleRel = new GroupRoleRelVO() ; 
		groupRoleRel.setRoleId ( roleId ) ; 
		groupRoleRel.setGrpId ( grpId ) ; 
		groupRoleRel.setOperUser ( operuser );
		groupDao.deleteGroupRoleRel ( groupRoleRel ) ; 
	}    	

	/*
	public List getGroupsByPaths( String[] grpPaths ) throws CheckException { 
		return groupDao.getGroupsByPaths ( grpPaths ) ;
	}
	*/
}